﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{
   
    public class ColaProductFunctionTestQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] ColaProductFunctionTestQuery CPFTQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (CPFTQ.PageNumber <= 0 || CPFTQ.PageSize <= 0)
            {
                
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "ColaProductFunctionTestQueryController:分页参数无效";
                RO.Data = null;
                Logger.Error("ColaProductFunctionTestQueryController:分页参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (CPFTQ.CPFT_ID != 0)
                    {
                        whereClause += " AND CPFTID = @ID";
                    }
                    if (CPFTQ.CPFT_Date.HasValue)
                    {
                        whereClause += " AND CPFTDate = @Date";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_LineBody))
                    {
                        whereClause += " AND CPFTLineBody LIKE @LineBody";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_ProductModel))
                    {
                        whereClause += " AND CPFTProductModel LIKE @ProductModel";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_OrderModel))
                    {
                        whereClause += " AND CPFTOrderModel LIKE @OrderModel";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_Inspector))
                    {
                        whereClause += " AND CPFTInspector LIKE @Inspector";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_InspectionItem))
                    {
                        whereClause += " AND CPFTInspectionItem LIKE @InspectionItem";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_TerminalTorque))
                    {
                        whereClause += " AND CPFTTerminalTorque LIKE @TerminalTorque";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_OverallPulloutForce))
                    {
                        whereClause += " AND CPFTOverallPulloutForce LIKE @OverallPulloutForce";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_SimulationInstallation))
                    {
                        whereClause += " AND CPFTSimulationInstallation LIKE @SimulationInstallation";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_HighVoltageTest))
                    {
                        whereClause += " AND CPFTHighVoltageTest LIKE @HighVoltageTest";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_ProbeTest))
                    {
                        whereClause += " AND CPFTProbeTest LIKE @ProbeTest";
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_ContactGaugeNonContactGaugeSocket))
                    {
                        whereClause += " AND CPFTContactGaugeNonContactGaugeSocket LIKE @ContactGaugeNonContactGaugeSocket";
                    }

                    var query = $@"
                        SELECT 
                            CPFTID, CPFTDate, CPFTLineBody, CPFTProductModel, CPFTOrderModel, 
                            CPFTInspector, CPFTInspectionItem, CPFTTerminalTorque, CPFTOverallPulloutForce, 
                            CPFTSimulationInstallation, CPFTHighVoltageTest, CPFTProbeTest, CPFTContactGaugeNonContactGaugeSocket,CPFTCreateCreator,CPFTCreateTime,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                CPFTID, CPFTDate, CPFTLineBody, CPFTProductModel, CPFTOrderModel, 
                                CPFTInspector, CPFTInspectionItem, CPFTTerminalTorque, CPFTOverallPulloutForce, 
                                CPFTSimulationInstallation, CPFTHighVoltageTest, CPFTProbeTest, CPFTContactGaugeNonContactGaugeSocket,CPFTCreateCreator,CPFTCreateTime,
                                ROW_NUMBER() OVER(ORDER BY CPFTID) AS RowNum
                             FROM ColaProductFunctionTest {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (CPFTQ.PageNumber - 1) * CPFTQ.PageSize + 1;
                    int endRow = CPFTQ.PageNumber * CPFTQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };
                    if (CPFTQ.CPFT_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = CPFTQ.CPFT_ID });
                    }
                    if (CPFTQ.CPFT_Date.HasValue)
                    {
                        parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime) { Value = CPFTQ.CPFT_Date });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_LineBody))
                    {
                        parameters.Add(new SqlParameter("@LineBody", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_LineBody}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_ProductModel))
                    {
                        parameters.Add(new SqlParameter("@ProductModel", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_ProductModel}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_OrderModel))
                    {
                        parameters.Add(new SqlParameter("@OrderModel", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_OrderModel}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_Inspector))
                    {
                        parameters.Add(new SqlParameter("@Inspector", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_Inspector}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_InspectionItem))
                    {
                        parameters.Add(new SqlParameter("@InspectionItem", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_InspectionItem}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_TerminalTorque))
                    {
                        parameters.Add(new SqlParameter("@TerminalTorque", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_TerminalTorque}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_OverallPulloutForce))
                    {
                        parameters.Add(new SqlParameter("@OverallPulloutForce", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_OverallPulloutForce}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_SimulationInstallation))
                    {
                        parameters.Add(new SqlParameter("@SimulationInstallation", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_SimulationInstallation}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_HighVoltageTest))
                    {
                        parameters.Add(new SqlParameter("@HighVoltageTest", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_HighVoltageTest}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_ProbeTest))
                    {
                        parameters.Add(new SqlParameter("@ProbeTest", SqlDbType.NVarChar, 50) { Value = $"%{CPFTQ.CPFT_ProbeTest}%" });
                    }
                    if (!string.IsNullOrEmpty(CPFTQ.CPFT_ContactGaugeNonContactGaugeSocket))
                    {
                        parameters.Add(new SqlParameter("@ContactGaugeNonContactGaugeSocket", SqlDbType.NVarChar, 100) { Value = $"%{CPFTQ.CPFT_ContactGaugeNonContactGaugeSocket}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("ColaProductFunctionTestQueryController:未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "ColaProductFunctionTestQueryController:未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var records = new List<ColaProductFunctionTest>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                records.Add(new ColaProductFunctionTest
                                {
                                    CPFT_ID = reader.GetInt32(reader.GetOrdinal("CPFTID")),
                                    CPFT_Date = reader.GetDateTime(reader.GetOrdinal("CPFTDate")),
                                    CPFT_LineBody = reader.GetString(reader.GetOrdinal("CPFTLineBody")),
                                    CPFT_ProductModel = reader.GetString(reader.GetOrdinal("CPFTProductModel")),
                                    CPFT_OrderModel = reader.GetString(reader.GetOrdinal("CPFTOrderModel")),
                                    CPFT_Inspector = reader.GetString(reader.GetOrdinal("CPFTInspector")),
                                    CPFT_InspectionItem = reader.GetString(reader.GetOrdinal("CPFTInspectionItem")),
                                    CPFT_TerminalTorque = reader.GetString(reader.GetOrdinal("CPFTTerminalTorque")),
                                    CPFT_OverallPulloutForce = reader.GetString(reader.GetOrdinal("CPFTOverallPulloutForce")),
                                    CPFT_SimulationInstallation = reader.GetString(reader.GetOrdinal("CPFTSimulationInstallation")),
                                    CPFT_HighVoltageTest = reader.GetString(reader.GetOrdinal("CPFTHighVoltageTest")),
                                    CPFT_ProbeTest = reader.GetString(reader.GetOrdinal("CPFTProbeTest")),
                                    CPFT_ContactGaugeNonContactGaugeSocket = reader.GetString(reader.GetOrdinal("CPFTContactGaugeNonContactGaugeSocket")),
                                    CPFT_CreateCreator = reader.GetString(reader.GetOrdinal("CPFTCreateCreator")),
                                    CPFT_CreateTime = reader.GetDateTime(reader.GetOrdinal("CPFTCreateTime")),
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = records;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = CPFTQ.PageNumber;
                            RO.PageSize = CPFTQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ColaProductFunctionTestQueryController:查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "ColaProductFunctionTestQueryController:Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}
